import { LoginResponse } from "@/api/types";
import { useEffect, useState } from "react";

export const USER_INFO_KEY = 'userInfo'

export default function useUserData() {
  const [userInfo, setUserInfo] = useState<LoginResponse['data'] | null>(null)

  function updateUserInfo(userInfo: LoginResponse['data']) {
    if (userInfo === null) {
      localStorage.removeItem(USER_INFO_KEY)
    } else {
      setUserInfo(userInfo)
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
    }
  }

  useEffect(() => {
    const userInfo = localStorage.getItem(USER_INFO_KEY)
    if (userInfo) {
      setUserInfo(JSON.parse(userInfo))
    }
  }, [])

  return { userInfo, updateUserInfo }
}

export function getUserInfo(): LoginResponse['data'] | null {
  const cacheData = localStorage.getItem(USER_INFO_KEY)
  return cacheData ? JSON.parse(cacheData) : null
}
